package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.JsonResult;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/emp")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    //为了在页面上显示对应的部门名称
    @Autowired
    private IDepartmentService departmentService;


    //分页查询
    //过滤查询也是一次请求满足条件的请求
    //EmployQueryObject既能封装分页、又能封装过滤参数
    @RequiredPermission(name = "员工页面", expression = "employee:list")
    @RequestMapping("/list")
    public String query(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);

        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);


        return "employee/list";
    }

    @RequestMapping("/input")
    @RequiredPermission(name = "员工新增/编辑", expression = "employee:saveOrUpdate")
    public String input(Model model, Employee employee) {
        //部门名称让用户选择
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);

        //角色权限让用户选择
        List<Role> roles = employeeService.getRoles();
        model.addAttribute("roles", roles);

        if (employee.getId() != null) {
            //不为空，则回显数据
            Employee emp = employeeService.selectOne(employee.getId());
            model.addAttribute("emp", emp);
        }
        //为空则不回显
        return "employee/input";
        //list.ftl的a标签---》EmployeeController的/emp/input--->到input.ftl文件
    }

    @RequiredPermission(name = "员工新增/编辑", expression = "employee:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids) {//角色权限的ids，是右边下拉框中被选中的selected的name
        //前端页面传过来的角色权限的
        if (employee.getId() != null) {
            employeeService.update(employee, ids);
        } else {
            employeeService.save(employee, ids);
        }

        return new JsonResult();
    }

    @RequiredPermission(name = "员工删除", expression = "employee:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        employeeService.delete(id);
        return "redirect:/emp/list";
    }

    @RequiredPermission(name = "员工导出", expression = "employee:exportXls")
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition", "attachment;filename=employee.xls");
       /* Workbook wb = new HSSFWorkbook();
        employeeService.exportXls();*/
        //调用service中的方法直接响应
        Workbook wb = employeeService.exportXls();
        //把excel的数据输出到浏览器
        wb.write(response.getOutputStream());
    }


    //异步提交新增用户时，查用户名是否已存在于数据库
    @RequestMapping("/checkUsername")
    @ResponseBody
    public Map<String, Boolean> checkUsername(String username) {
        Map<String, Boolean> map = new HashMap<>();
        Employee employee = employeeService.selectByUsername(username);
        /*if (employee == null){//对象为空，则可以注册
           map.put("valid",false);
           return map;
        }
        map.put("valid",true);
        return map;*/
        map.put("valid", employee == null);
        return map;
    }

    @RequestMapping("/nopermission")
    public String nopermission() {
        return "/common/nopermission";
    }

    //账号状态设置
    @RequestMapping("/setStatus")
    public JsonResult setStatus(Model model, Employee employee) {

        employeeService.updateUserStatus(employee.getId(), employee.isStatus());
        Employee employee1 = employeeService.selectOne(employee.getId());

        return new JsonResult();
    }

    //批量删除
    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Model model, Long[] ids) {
        //ajax请求已经将所有的请求数据都发送了过来
        employeeService.batchDelete(ids);
        return new JsonResult();
    }

    //修改密码
    @RequestMapping("/update")
    public String updatePasswordById(Model model, Long id) {
        //先查用户
        Employee employee = employeeService.selectOne(UserContext.getCurrentUser().getId());
        model.addAttribute("employee", employee);
        return "/employee/updatePwd";
    }

    //修改密码
    @RequestMapping("/updatePasswordById")
    @ResponseBody
    public JsonResult updatePasswordById(Long id, String password, String newPassword) {

        //原始密码与新传过来的密码不同则提示
        Employee employee1 = employeeService.selectOne(id);
        if (!(password.equals(employee1.getPassword()))) {
            return new JsonResult(false, "两次密码不一致");
        }
        employeeService.updateById(id, newPassword);
        UserContext.getSession().invalidate();

        return new JsonResult();



    }
}
